package com.kun.rental.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kun.rental.entity.Dept;
import com.kun.rental.mapper.DeptMapper;
import com.kun.rental.service.IDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kun.rental.utils.DeptTreeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ikun
 * @since 2024-07-04
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    @Autowired
    private DeptMapper deptMapper;

    /**
     * 查询部门列表
     * @param dept
     * @return
     */
    @Override
    public List<Dept> selectList(Dept dept) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotEmpty(dept.getDeptName()),
                "dept_name", dept.getDeptName());
        queryWrapper.orderByAsc("order_num");
        List<Dept> depts = deptMapper.selectList(queryWrapper);
        //查询每个部门的子部门
        return DeptTreeUtils.buildTree(depts,0);
    }

    /**
     * 查询并构建上级部门树结构
     * @return List<Dept> 返回构建好的部门树结构列表
     */
    @Override
    public List<Dept> selectTree() {
        // 创建查询条件，不指定特定条件，查询所有部门，并按照“order_num”升序排列
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("order_num");

        // 执行查询，获取所有部门的列表
        List<Dept> depts = deptMapper.selectList(queryWrapper);

        // 创建并添加根节点到部门列表，根节点用于展示所有部门，其ID设为0，父ID设为-1
        Dept dept = new Dept();
        dept.setDeptName("所有部门").setId(0).setPid(-1);
        depts.add(dept);

        // 调用工具类方法，将部门列表转换为树结构列表，根节点的父ID设为-1
        return DeptTreeUtils.buildTree(depts, -1);
    }

    /**
     * 判断部门下是否有子部门
     * @param id
     * @return
     */
    @Override
    public boolean hasChildren(Integer id) {
        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", id);
        return baseMapper.selectCount(queryWrapper) > 0;
    }
}
